var http = require('http');
var fs = require('fs');

// 路由 - 后端服务器，根据前端访问的路径，返回不同的内容
var myServer = http.createServer(function (request, response) {
  var url = request.url;
  console.log('接收到前端发送的请求：', url);

  if (url == '/home') {
    response.writeHead(200, {
      'Content-Type': 'text/html'
    });
    response.write('<h1>home</h1>');
    response.end();
  } else if (url == '/image') {
    // 读取图片不需要设置编码
    fs.readFile('public/images/default.png', function (err, data) {
      response.writeHead(200, {
        'Content-Type': 'image/jpeg'
      });
      response.write(data);
      response.end();
    });
  } else if (url == '/') {
    response.writeHead(200, {
      'Content-Type': 'text/plain'
    });

    response.write('hello world');
    response.end();
  } else {
    response.writeHead(404, {
      'Content-Type': 'text/plain'
    });

    // 响应内容
    response.write('404');
    response.end();
  }
});

myServer.listen(3030);